//
//  HMComposeEmotionKeybord.swift
//  Weibo
//
//  Created by 李学林 on 15/12/15.
//  Copyright © 2015年 tete. All rights reserved.
//

import UIKit
/// 可重用id
private let HMEmoticonCollectionViewId = "HMEmoticonCollectionViewId"

class HMComposeEmotionKeybord: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /**
     设置UI
     */
    private func setupUI(){
        backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        
        // 添加子控件
        addSubview(toolBar)
        addSubview(emoticonCollectionView)
        addSubview(emoticonPageControl)
        
        // 设置约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(self)
            make.trailing.equalTo(self)
            make.leading.equalTo(self)
            make.height.equalTo(37)
        }
        emoticonCollectionView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self)
            make.width.equalTo(self)
            make.bottom.equalTo(toolBar.snp_top)
            make.leading.equalTo(self)
        }
        emoticonPageControl.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
    }
    
    
    override func layoutSubviews() {
        super.layoutSubviews()
        let layout = emoticonCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = emoticonCollectionView.size
    }
    
    // MARK: - 懒加载控件
    // toolBar

    lazy var toolBar: HMEmoticonToolBar = {
    
        let toolBar = HMEmoticonToolBar(frame: CGRectZero)
        toolBar.delegate = self
//        toolBar.backgroundColor = RandomColor()
        return toolBar
    }()
    
    
    /// 懒加载emoticonPageControl
    lazy var emoticonPageControl: UIPageControl = {
        let pageControl = UIPageControl()
        pageControl.setValue(UIImage(named: "compose_keyboard_dot_selected"), forKeyPath: "_currentPageImage")
        pageControl.setValue(UIImage(named: "compose_keyboard_dot_normal"), forKeyPath: "_pageImage")
        
        return pageControl
        
    }()
    
    /// 表情键盘中间的collectionView
    lazy var emoticonCollectionView: UICollectionView = {
       
        // 初始化layout
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
     /// 初始化键盘中间的collectionView
    let emoticonCollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
        emoticonCollectionView.backgroundColor = UIColor.clearColor()
        emoticonCollectionView.dataSource = self
        emoticonCollectionView.delegate = self
        emoticonCollectionView.bounces = false
        emoticonCollectionView.showsHorizontalScrollIndicator = false
        emoticonCollectionView.showsVerticalScrollIndicator = false
        emoticonCollectionView.pagingEnabled = true
        // 注册cell
        emoticonCollectionView.registerClass(HMEmoticonPageView.self, forCellWithReuseIdentifier: HMEmoticonCollectionViewId)
        return emoticonCollectionView
    }()
    
}
// MARK: UICollectionViewDataSource,UICollectionViewDelegate代理方法
extension HMComposeEmotionKeybord: UICollectionViewDataSource, UICollectionViewDelegate{

    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        let num = HMEmoticonTools.shareTools.allEmoticons.count
        printLog(num)
        return num
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let num = HMEmoticonTools.shareTools.allEmoticons[section].count
        printLog(num)
        
        return HMEmoticonTools.shareTools.allEmoticons[section].count
        
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(HMEmoticonCollectionViewId, forIndexPath: indexPath) as! HMEmoticonPageView
        
        cell.indexPath = indexPath
        
        // 赋值
        cell.emoticons = HMEmoticonTools.shareTools.allEmoticons[indexPath.section][indexPath.item]
        
        return cell
    }
    
    // ***************************************************************************
    // 监听滚动
    func scrollViewDidScroll(scrollView: UIScrollView) {
        // 1. 取到界面上显示的 cell
        let cells = emoticonCollectionView.visibleCells()
        printLog(cells.count)
        // 2. 判断哪一个 cell 在界面上显示得多
        if cells.count == 2 {
            
            // 取到两个 cell
            let firstCell = cells.first!
            let secondCell = cells.last!
            
            // 判断哪一个 cell 在界面上显示得多 --> 怎么判断
            // contenOffset
            // 拿 cell 的 x 与 contentOffset.x 值进入相差,取绝对值
            // 哪个绝对值小,哪一个就显示得多
            
            let firstCellR = abs(Int32(firstCell.x - scrollView.contentOffset.x))
            let secondCellR = abs(Int32(secondCell.x - scrollView.contentOffset.x))
            
            let cell: UICollectionViewCell
            if firstCellR < secondCellR {
                // 第一个显示得多
                cell = firstCell
            }else{
                // 第二个显示得多
                cell = secondCell
            }
            // 根据哪一个cell 在界面显得多,取到其在 collectionView 中的 indexPath
            let indexPath = emoticonCollectionView.indexPathForCell(cell)!
            // printLog("当前是第 \(indexPath.section) 组")
            // 从 toolBar 找对对应表情类型的按钮.让其选中,让之前的取消选中
            // 只要告诉 toolBar 当前滚动到第几组就可以了.其一概不管
            toolBar.currentSection = indexPath.section
            //  toolBar.viewWithTag(indexPath.section)
            setPageControlData(indexPath)
            
        }
    }
    
    //************************************************************************
    
}

// MARK: - HMEmoticonToolBarDelegate 按钮点击的方法
extension HMComposeEmotionKeybord: HMEmoticonToolBarDelegate {
    
    func didselectedButtonWithType(type: HMEmoticonType) {
        
        let  indexPath : NSIndexPath?
        
        switch type{
        case .Recent:
            
            indexPath = NSIndexPath(forItem: 0, inSection: 0)
            print("最近")
        case .Default:
            
            indexPath = NSIndexPath(forItem: 0, inSection: 1)
            print("默认")
        case .Emoji:
            indexPath = NSIndexPath(forItem: 0, inSection: 2)
            print("Emoji")
        case .Lxh:
            indexPath = NSIndexPath(forItem: 0, inSection: 3)
            print("浪小花")
            
        }
        // 点击按钮时让emoticonCollectionView滚动到正确的位置
        emoticonCollectionView.scrollToItemAtIndexPath(indexPath!, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
            setPageControlData(indexPath!)
    }
    
    private func setPageControlData(indexPath: NSIndexPath){
        // 设置 pageControl 的数据
        emoticonPageControl.numberOfPages = HMEmoticonTools.shareTools.allEmoticons[indexPath.section].count
        emoticonPageControl.currentPage = indexPath.item
        // 如果是第一个section pagecontrol控件就隐藏
        emoticonPageControl.hidden = (indexPath.section == 0)
    }
    
}
